package fr.starn.domoticz_widgets;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import fr.starn.domoticz_widgets.JSonObject.DeviceProps;
import fr.starn.domoticz_widgets.JSonObject.DevicesProps;

import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class ConfigureWidgetActivity extends Activity implements OnClickListener, IValueReceiver{

	private int widgetID;
	
	Context context;
	
	Button okButton;
	CheckBox authentCheckBox;
	EditText login;
	EditText password;
//	boolean ssl;
//	String hostnameStr;
//	int portInt;
//	String loginStr;
//	String passwordStr;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//manage widgetID
		widgetID = AppWidgetManager.INVALID_APPWIDGET_ID;
		Intent intent = getIntent();
	      Bundle extras = intent.getExtras();
	      if (extras != null) {
	         widgetID = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
	       }
	      //No valid ID, so bail out.
	      if (widgetID == AppWidgetManager.INVALID_APPWIDGET_ID){
	          finish();
	      }
	      
	      
		setContentView(R.layout.configure_widget1);
		
		this.context=getApplicationContext();
		
		
		

				login= (EditText)findViewById(R.id.login);
				password=(EditText)findViewById(R.id.password);
				EditText hostname= (EditText)findViewById(R.id.hostname);
				EditText portEditText = (EditText)findViewById(R.id.port);
				authentCheckBox= (CheckBox)findViewById(R.id.authCheckBox);
				authentCheckBox.setOnClickListener(this);
				WidgetPropertiesBean lastWidgetParams = WidgetPropertiesBean.loadAnyWidgetData(context);
				if ( lastWidgetParams!=null){
					String loginStr = lastWidgetParams.getLogin();
					if (loginStr != null && !"".equals(loginStr)){
						authentCheckBox.setChecked(true);
						login.setEnabled(true);
						password.setEnabled(true);
					} else {
						authentCheckBox.setChecked(false);
						login.setEnabled(false);
						password.setEnabled(false);
					}
					login.setText(loginStr);
					password.setText(lastWidgetParams.getPassword());
					hostname.setText(lastWidgetParams.getHost());
					portEditText.setText(""+lastWidgetParams.getPort());
					RadioGroup radioGroup = (RadioGroup)findViewById(R.id.protocol);
					if (lastWidgetParams.isSecured()){
						 ((RadioButton)findViewById(R.id.protocolHttps)).setChecked(true);
					} else {
						((RadioButton)findViewById(R.id.protocolHttp)).setChecked(true);
					}
				}

		
		
		okButton = (Button)findViewById(R.id.okButton);
		okButton.setOnClickListener(this);
		


		
//		portEditText.setText(""+portInt);
//		login.setText(loginStr);
//		password.setText(passwordStr);
//		hostname.setText(hostnameStr);
//		RadioGroup radioGroup = (RadioGroup)findViewById(R.id.protocol);
//		if (ssl) {
//			radioGroup.check(1);
//		} else {
//			radioGroup.check(0);
//		}
		
		
	}


	


	@Override
	public void onClick(View view) {
		if ("okButton".equals(view.getTag())){
			TextView login;
			TextView password;
			TextView hostname;
			TextView portEditText;
			boolean ssl;
			login = (TextView)findViewById(R.id.login);
			password = (TextView)findViewById(R.id.password);
			hostname = (TextView)findViewById(R.id.hostname);
			portEditText = (TextView)findViewById(R.id.port);
			
			
			RadioGroup radioGroup = (RadioGroup)findViewById(R.id.protocol);
		    int id= radioGroup.getCheckedRadioButtonId();
		    String protocolStr="";
		    if (id!=-1){
			    View radioButton = radioGroup.findViewById(id);
			    int radioId = radioGroup.indexOfChild(radioButton);
			    if (radioId==-1){
					Toast.makeText(this.getApplicationContext(),"You must select a protocol", Toast.LENGTH_LONG).show();
					return;
			    }
			    RadioButton btn = (RadioButton) radioGroup.getChildAt(radioId);
			    protocolStr = (String) btn.getText().toString();
				ssl = "https".equals(protocolStr);
		    } else {
				Toast.makeText(this.getApplicationContext(),"You must select a protocol", Toast.LENGTH_LONG).show();
				return;
		    }
			
			
			int port =  -1;
			String portStr = portEditText.getText().toString();
			try {
				port = Integer.parseInt(portStr);
			} catch (NumberFormatException e){
				Toast.makeText(this.getApplicationContext(),"Port "+portStr+" is incorrect", Toast.LENGTH_LONG).show();
				return;
			}
		

		
		
			WidgetPropertiesBean props = new WidgetPropertiesBean(0,ssl, hostname.getText().toString(),port,login.getText().toString(),password.getText().toString(),null);
			new Thread(new RestRequestHandler(context, this,props,RestRequestHandler.LIST)).start();
		}
		
		if ("authCheckBox".equals(view.getTag())){
			boolean value = authentCheckBox.isChecked();
			login.setEnabled(value);
			password.setEnabled(value);
		}
		
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode==0){
			if (resultCode == RESULT_OK) {


				String selectedDevice = data.getStringExtra("result"); 
				
				
				TextView login= (TextView)findViewById(R.id.login);
				TextView password=(TextView)findViewById(R.id.password);
				TextView hostname= (TextView)findViewById(R.id.hostname);
				TextView portEditText = (TextView)findViewById(R.id.port);
				RadioGroup radioGroup = (RadioGroup)findViewById(R.id.protocol);
				boolean ssl = radioGroup.getCheckedRadioButtonId()==1;
				int portInt = Integer.parseInt(portEditText.getText().toString());
				
				
				WidgetPropertiesBean props = new WidgetPropertiesBean(widgetID, ssl,hostname.getText().toString(),portInt,login.getText().toString(),password.getText().toString(),selectedDevice);
				WidgetPropertiesBean.saveToPreferences(this,props);
				
				Intent resultValue = new Intent();
			    resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetID);
			    setResult(RESULT_OK, resultValue);
			    
		        Intent intent = new Intent(context, TempWidgetProvider.class);
		        intent.putExtra("props",props);
		        intent.setAction(TempWidgetProvider.SYNC_CLICKED);
		        try {
		        	PendingIntent.getBroadcast(context, props.getWidgetID(), intent, PendingIntent.FLAG_UPDATE_CURRENT).send();
		        } catch (Exception e){
		        	e.printStackTrace();
		        }
			    finish();
			}
		}
	}

	@Override
	public void updateValue(Context contextNull, WidgetPropertiesBean props, DevicesProps result) {
		Intent intent= new Intent(this.getApplicationContext(), ConfigureWidgetStep2.class);
		intent.putExtra("devicesJSON", result.serialize());
		startActivityForResult(intent,0);
	}



	@Override
	public void manageError(Context context, WidgetPropertiesBean props, String error) {
		Intent intent= new Intent(this.getApplicationContext(), ShowPopUpActivity.class);
		intent.putExtra("error", error);
		startActivity(intent);
	}
	

    


}
